import router from '@/router'
import { Module } from 'vuex'
import localCache from '@/utils/cache'
import { mapMenusToRouters } from '@/utils/map-menus'
import { IRootState } from '../type'
import { accountLoginRequest } from '@/service/login/login'
interface IloginState {
  token: string
  userInfo: any
  userMenus: any
}

const loginModule: Module<IloginState, IRootState> = {
  namespaced: true, //命名空间
  state: () => {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      // const routes = mapMenusToRouters(userMenus)
      // routes.forEach((item) => {
      //   router.addRoute('main', item)
      // })
      // console.log(routes)
    },
  },
  getters: {},
  actions: {
    // 登录 普通用户登录接口
    async accountLoginOrdinary({ commit }, payload: any) {
      // 1.实现登录逻辑
      const loginReslut = await accountLoginRequest(payload)
      console.log(loginReslut)
      // 2.拿到用户信息
      // 3.请求用户菜单

      // 4.跳转到首页
    },

    // 后台登录接口
    async accountLogin({ commit }, payload: any) {
      // 1.实现登录逻辑
      const loginReslut = await accountLoginRequest(payload)
      const token = loginReslut.result.accessToken
      // 3.请求用户菜单
      const userMenus = [
        {
          id: 38,
          name: '菜单',
          type: 1,
          url: '/setting',
          icon: 'el-icon-monitor',
          sort: 1,
          children: [
            {
              id: 39,
              url: '/setting/user',
              name: '用户',
              sort: 106,
              type: 2,
              children: null,
            },
            {
              id: 40,
              url: '/setting/role',
              name: '角色',
              sort: 107,
              type: 2,
              children: null,
            },
            {
              id: 43,
              url: '/setting/tenant',
              name: '租户',
              sort: 108,
              type: 2,
              children: null,
            },
          ],
        },
      ]
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)
      //token存入
      commit('changeToken', token)
      localCache.setCache('token', token)
      // 4.跳转到后台首页
      router.push('/setting')
    },
    // 5.获取本地缓存中的数据到vuex
    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    },
  },
}
export default loginModule
